package register

import AuthRepository
import BaseViewModel
import LoadingStatus
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import register.models.RegisterEvent
import register.models.RegisterViewState

class RegisterViewModel(
    private val repository: AuthRepository
) : BaseViewModel<RegisterViewState, RegisterEvent>(
    RegisterViewState()
) {
    override fun obtainEvent(event: RegisterEvent) {
        when (event) {
            is RegisterEvent.UsernameChanged -> {
                updateState { it.copy(username = event.username) }
            }

            is RegisterEvent.PasswordChanged -> {
                updateState { it.copy(password = event.password) }
            }

            is RegisterEvent.PasswordConfirmationChanged -> {
                updateState { it.copy(passwordConfirmation = event.passwordConfirmation) }
            }

            is RegisterEvent.RegisterClicked -> {
                if (viewState.password != viewState.passwordConfirmation) {
                    updateState {
                        it.copy(
                            loadingStatus = LoadingStatus.Error(
                                "Пароли должны совпадать"
                            )
                        )
                    }
                    return
                }
                updateState { it.copy(loadingStatus = LoadingStatus.Loading) }
                viewModelScope.launch {
                    repository.register(
                        viewState.username,
                        viewState.password
                    )
                        .onSuccess { updateState { it.copy(loadingStatus = LoadingStatus.FullyLoad) } }
                        .onFailure { t ->
                            updateState {
                                it.copy(
                                    loadingStatus = LoadingStatus.Error(
                                        t.message
                                    )
                                )
                            }
                        }
                }
            }
        }
    }
}